package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private HuanXinService huanXinService;

    @Value("${jwt.secret}")
    private String secret;

    /**
     * 校验验证码和将用户基础信息存储到数据库
     * @param mobile
     * @param code
     * @return
     */
    public String login(String mobile, String code) {
        String redisKey = "CHECK_CODE_" + mobile;
        String value = (String) redisTemplate.opsForValue().get(redisKey);

        //判断验证码是否为空
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        //判断验证码是否一致
        if (!StringUtils.equals(code, value)) {
            return null;
        }

        //默认不是新用户
        Boolean isNew=false;

        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        User selectUser = userMapper.selectOne(queryWrapper);
        if (selectUser==null){
            //数据库没有该用户,存入数据库
            User user=new User();
            user.setMobile(mobile);
            user.setPassword(DigestUtils.md5Hex(secret + "_123456"));
            userMapper.insert(user);
            isNew=true;
            selectUser=user;

            //注册到环信
            huanXinService.register(user.getId());
        }

        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("mobile", mobile);
        claims.put("id", selectUser.getId());

        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //设置响应数据体
                .signWith(SignatureAlgorithm.HS256,secret) //设置加密方法和加密盐
                .compact();

        //将数据写到redis中
        String redisTokenKey="TOKEN_"+token;

        try {
            redisTemplate.opsForValue().set(redisTokenKey,MAPPER.writeValueAsString(selectUser), Duration.ofHours(1));
        } catch (Exception e) {
            e.printStackTrace();
        }

        //MQ
        try {
            // 发送登录成功的消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("userId", selectUser.getId());
            msg.put("date", new Date());
            this.rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return isNew+"|"+token;
    }


    /**
     *从redis中获取token
     * @param token
     * @return
     */
    public User queryUserByToken(String token) {
        try {
            String redisTokenKey = "TOKEN_" + token;
            String cacheData = this.redisTemplate.opsForValue().get(redisTokenKey);
            if (StringUtils.isEmpty(cacheData)) {
                return null;
            }
            // 刷新时间
            this.redisTemplate.expire(redisTokenKey, 1, TimeUnit.HOURS);
            return MAPPER.readValue(cacheData, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更改手机号
     * @param id
     * @param newPhone
     * @return
     */
    public boolean updatePhone(Long id, String newPhone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", newPhone);
        User user = this.userMapper.selectOne(queryWrapper);
        if (user != null) {
            // 改手机号已经存在
            return false;
        }
        user = new User();
        user.setId(id);
        user.setMobile(newPhone);
        return this.userMapper.updateById(user) > 0;
    }
}
